package jt

import (
	"encoding/json"
	"fmt"
	"strconv"
	"strings"
	"time"

	"github.com/axgle/mahonia"
)

const (
	timeFormat = "2006-01-02 15:04:05"
)

// toUnixTime 格式化字符串为时间戳
func toUnixTime(dt string) int64 {
	tm, _ := time.Parse(timeFormat, dt)
	return tm.Unix()
}

// UnixToTime 格式化时间戳为字符串
func unixToTime(stamp int64) string {
	var cstzone = time.FixedZone("CST", 0)
	return time.Unix(stamp, 0).In(cstzone).Format(timeFormat)
}

func nowBytes() (r []byte) {
	s := time.Now().Format(timeFormat)
	b := []byte(s)
	r = append(r, b[2:4]...)
	r = append(r, b[5:7]...)
	r = append(r, b[8:10]...)
	r = append(r, b[11:13]...)
	r = append(r, b[14:17]...)
	r = append(r, b[17:19]...)
	return r
}

// Bcd2Number bcd解码
func bcd2Number(bcd []byte) string {
	var number string
	for _, i := range bcd {
		number += fmt.Sprintf("%02X", i)
	}
	pos := strings.LastIndex(number, "F")
	if pos == 8 {
		return ""
	}
	return number[pos+1:]
}

// Hex2Byte Hex转[]byte
func hex2Byte(str string) []byte {
	slen := len(str)
	bHex := make([]byte, len(str)/2)
	ii := 0
	for i := 0; i < len(str); i = i + 2 {
		if slen != 1 {
			ss := string(str[i]) + string(str[i+1])
			bt, _ := strconv.ParseInt(ss, 16, 32)
			bHex[ii] = byte(bt)
			ii = ii + 1
			slen = slen - 2
		}
	}
	return bHex
}

// Number2bcd bcd解码
func number2bcd(number string) []byte {
	var rNumber = number
	for i := 0; i < 8-len(number); i++ {
		rNumber = "f" + rNumber
	}
	bcd := hex2Byte(rNumber)
	return bcd
}

// CheckSum 计算
func checkSum(b []byte) uint8 {
	ret := b[0]
	for i := 1; i < len(b); i++ {
		ret ^= b[i]
	}
	return ret
}

var (
	dec = mahonia.NewDecoder("gbk")
	enc = mahonia.NewEncoder("gbk")
)

func toUTF8(data []byte) string {
	return dec.ConvertString(string(data))
}

func toGBK(str string) []byte {
	return []byte(enc.ConvertString(str))
}

func hexToUint16(s string) uint16 {
	v, _ := strconv.ParseUint(s[2:], 16, 32)
	return uint16(v)
}

func strToInt(s string) int {
	val, _ := strconv.Atoi(s)
	return val
}

func strToUInt8(s string) uint8 {
	val, _ := strconv.Atoi(s)
	return uint8(val)
}

func strToInt64(s string) int64 {
	v, _ := strconv.ParseInt(s, 10, 64)
	return v
}

func jsonVal(s, v interface{}) error {
	b, err := json.Marshal(s)
	if err == nil {
		err = json.Unmarshal(b, v)
	}
	return err
}
